import mx.utils.Delegate;

import gugga.application.SectionsTransition;
import gugga.common.EventDescriptor;
import gugga.sequence.FictiveTask;
import gugga.sequence.PreconditionsTask;
import gugga.sequence.ProgressMonitor;
import gugga.utils.DoLaterUtil;

/**
 * @author Todor Kolev
 * TODO: Should implement ISectionsTransition instead of extending SectionsTransition
 */
class gugga.application.FictiveSectionsTransition extends SectionsTransition
{
	private var mFictiveLoadingTask : FictiveTask;
	private var mCompletionPreconditionsTask : PreconditionsTask;
	
	public function FictiveSectionsTransition(aCompletionPrecondition : EventDescriptor) 
	{
		mFictiveLoadingTask = new FictiveTask();
		
		mPreOpenProgressMonitor = new ProgressMonitor();
		mPreOpenProgressMonitor.addTask(mFictiveLoadingTask);
		mPreOpenProgressMonitor.start();
		
		if(aCompletionPrecondition)
		{
			mCompletionPreconditionsTask = new PreconditionsTask();
			mCompletionPreconditionsTask.add(aCompletionPrecondition);
			
			mCompletionPreconditionsTask.addEventListener("completed", 
				Delegate.create(this, onCompletionPreconditionsTaskCompleted));
		}
	}

	public function start() : Void
	{
		mIsRunning = true;
		dispatchEvent({type: "start", target: this});
		
		DoLaterUtil.doLater(this, doMiddlePointTasks, null, 1);
	}
	
	private function doMiddlePointTasks() : Void
	{
		mFictiveLoadingTask.start();
		dispatchEvent({type: "sectionsSwapped", target: this});
		
		if(mCompletionPreconditionsTask)
		{
			mCompletionPreconditionsTask.start();
		}
		else
		{
			DoLaterUtil.doLater(this, complete, null, 1);
		}
	}
	
	public function canInterrupt() : Boolean
	{
		return false;
	}
	
	private function complete()
	{	
		mIsRunning = false;
		dispatchEvent({type: "completed", target: this});
		dispatchEvent({type: "disposed", target: this});
	}
	
	private function onCompletionPreconditionsTaskCompleted(aEvent : Object) : Void 
	{
		complete();	
	}
}